import { createRouter, createWebHashHistory } from 'vue-router'
import routes from './module/routes'
import { getItem } from '@/utils/token'

const router = createRouter({
  linkActiveClass: 'active',
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  // 更改标题
  if (to.meta.title) {
    document.title = to.meta.title
  }

  // 路由守卫
  const token = getItem('TOKEN')
  if (token) {
    // 用户是否去登录页面
    if (to.path === '/login' || to.path === '/register') {
      next(`?redirect=${to.name}`)
    } else {
      next()
    }
  } else {
    const arr = ['/bookKeeping', '/community', '/community/publish', '/personal']
    if (arr.includes(to.path)) {
      next(`/login?redirect=${to.name}`)
    } else {
      next()
    }
  }
})

export default router
